import React from "react";

interface AbcState {
    sessionKey: any,
    isAuth: Boolean,
    tip: string
}

const AUTH = 'chromeExtensionAuth';

class App extends React.Component<{}, AbcState> {
    constructor(props: any) {
        super(props);
        this.state = {
            sessionKey: '',
            isAuth: false,
            tip: '扫码关注公众号，发送 1 ，然后将获取的 验证码 填写到输入框中，点击确定开始使用'
        };
        this.handleChange = this.handleChange.bind(this);
        this.getAuth = this.getAuth.bind(this)
    }

    componentDidMount(): void {
        let chromeExtensionAuth = localStorage.getItem(AUTH);
        if (chromeExtensionAuth)
            this.setState({isAuth: true});
        else
            this.setState({isAuth: false})
    }

    getCurrentTabId(callback: any) {
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
            if (callback) callback(tabs.length ? tabs[0].id : null)
        })
    }

    sendMessageToContentScript(message: Object, callback: any) {
        this.getCurrentTabId((tabId: number) => {
            chrome.tabs.sendMessage(tabId, message, function (response) {
                if (callback) callback(response);
            });
        });
    }

    handleChange(event: any) {
        this.setState({
            sessionKey: event.target.value
        })
    }

    getAuth() {
        const requestOptions = {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        };
        let sessionKey = this.state.sessionKey;
        fetch('http://ithub.api.maopuyu.com/ithub/api/chrome/handlerLogic/' + sessionKey, requestOptions).then(response => response.json()).then(result => {
            if (result.err == 0) {
                localStorage.setItem(AUTH, sessionKey);
                this.setState({isAuth: true})
            } else {
                this.setState({tip: '抱歉，您输入的验证码不正确'})
            }
        })
    }
    render() {
        if (this.state.isAuth)
            return (<button onClick={() => this.sendMessageToContentScript({cmd: 'down_good_list'}, function () {
            })}>下载商品列表</button>);
        return (
            <div>
                <img style={{width: 120}} src="http://imgs.maopuyu.com/qrcode_for_gh_1f012feb4af9_258.jpg"
                     alt="入学观察二维码"/>
                <div>{this.state.tip}</div>
                <div>
                    <input type="text" value={this.state.sessionKey} onChange={this.handleChange}/>
                    <button onClick={() => this.getAuth()}>确定</button>
                </div>
            </div>
        );
    }
}
export default App;